#include "task.h"
#include "taask.h"
#include "schedule.h"
#include "thread_create.h"

#define error -1
#define sucessed 0

int task_create(unsigned char *task_name, unsigned long task_stack_size, thread_func task_func, unsigned char pority)
{
    match_sizetype *pstack = NULL;
    TCB *p_tcb = NULL;

    pstack = (match_sizetype *)malloc(task_stack_size * sizeof(match_sizetype));

    if (!pstack)
    {
        printf("statck init error\n");
        return error;
    }

    p_tcb = (TCB *)malloc(sizeof(TCB));
    memset(p_tcb, 0, sizeof(TCB));

    if (!p_tcb)
    {
        printf("tcb alloc error\n");
        return error;
    }

    p_tcb->task_stack = pstack;
    p_tcb -> stackEnd = pstack;
    p_tcb -> pority = pority;

    p_tcb->runtime_counter = 0;
    p_tcb->assigned_time = 10;    //guess time slice 1000 ticks

    //allign stack top addr ,32 bits allign
    p_tcb ->stackTop = (match_sizetype *)((match_sizetype)(&pstack[task_stack_size-1]) & (~(match_sizetype)(32 -1)));

    //check stack if allign
    if ((match_sizetype)(p_tcb->stackTop) & ((match_sizetype)(32 - 1)))
    {
        printf("allign error of stack top\n");
        return error;
    }

	//low name assigned
    int i = 0;
    while(i < 16)
    {
        p_tcb->taskname[i] = task_name[i];
        if (task_name[i] == '\0')
            break;
		if (15 == i)
			p_tcb->taskname[i] = '\0';

		i++;
    }

    //hold this task start
    if (task_thread_init(p_tcb, task_func))
    {
        printf("task create error\n");
        return error;
    }

    PostReadylist(p_tcb);


    return sucessed;

}
